package com.chart.web.controller.chart;
import com.chart.chart.domian.req.PUReq;
import com.chart.chart.domian.resp.UserResp;
import com.chart.chart.domian.vo.PUVo;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.ChartClick;
import com.chart.common.utils.SecurityUtils;
import com.chart.common.utils.poi.ExcelUtil;
import com.chart.system.service.IChartClickService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("chart/click")
//@Slf4j
public class ChartClickController {
    private static final Logger log = LoggerFactory.getLogger(ChartClickController.class);

    @Autowired
    private IChartClickService chartClickService;





    @PostMapping("/saveClick")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveClick(@RequestBody ChartClick clickDTO) {
        try {
            if (clickDTO == null) {
                log.error("ClickDTO 不能为空");
                return AjaxResult.error("ClickDTO 不能为空");
            }
            if (clickDTO.getChartId() == null || clickDTO.getType() == null) {
                log.error("缺少参数: type 或 chartId");
                return AjaxResult.error("type或chartId 参数为空");
            }

            ChartClick click = new ChartClick();
            click.setChartId(clickDTO.getChartId());
            click.setType(clickDTO.getType());

            // 获取 userId 并检查
            Long userId = SecurityUtils.getUserId();
            if (userId == null) {
                log.error("用户ID不能为空");
                return AjaxResult.error("用户ID不能为空");
            }
            click.setUserId(userId);

            log.info("保存点击记录: chartId={}, userId={}, type={}", click.getChartId(), click.getUserId(), click.getType());

            // 尝试保存记录
            boolean save = chartClickService.save(click);
            if (save) {
                log.info("保存成功: {}", click);
                return AjaxResult.success("保存成功");
            } else {
                log.warn("保存失败: {}", click);
                return AjaxResult.error("保存失败");
            }
        } catch (Exception e) {
            // 捕获异常并记录日志
            log.error("保存过程中出现异常", e);
            return AjaxResult.error("保存过程中出现异常: " + e.getMessage());
        }
    }




    /**
     * PV查询
     * @return
     */
   //  PV查询
    @GetMapping("queryPV")
    public  AjaxResult queryPV(){
   List<ChartClick> PV= chartClickService.queryPV();
        return AjaxResult.success(PV);
    }

    /**
     * UV查询
     * @return
     */

//    @GetMapping("queryPU")
//    public  AjaxResult queryUV(){
//        List<ChartClick> UV= chartClickService.queryUV();
//        return AjaxResult.success(UV);
//    }



    @PostMapping("queryPU")
    public  AjaxResult queryUV(@RequestBody PUReq req){
        List<PUVo> list = chartClickService.queryPU(req);
        return AjaxResult.success(list);
    }





    @ApiOperation("专家图例基础制图点击次数")
    @PostMapping("queryPU/export")
    public void export(HttpServletResponse response, @RequestBody PUReq req) {
        List<PUVo> list = chartClickService.queryPU(req);
        ExcelUtil<PUVo> util = new ExcelUtil<PUVo>(PUVo.class);
        util.exportExcel(response, list, "用户数据");
    }
//
//    @PostMapping("queryPU/export")
//    public ResponseEntity<byte[]> exportPU(@RequestBody PUReq req) throws IOException {
//        List<PUVo> list = chartClickService.queryPU(req);
//
//        // 创建工作簿和工作表
//        Workbook workbook = new XSSFWorkbook();
//        Sheet sheet = workbook.createSheet("PU Data");
//
//        // 创建表头
//        Row headerRow = sheet.createRow(0);
//        headerRow.createCell(0).setCellValue("项目名字");
//        headerRow.createCell(1).setCellValue("PV");
//        headerRow.createCell(2).setCellValue("UV");
//
//        // 填充数据
//        for (int i = 0; i < list.size(); i++) {
//            PUVo puVo = list.get(i);
//            Row row = sheet.createRow(i + 1);
//            row.createCell(0).setCellValue(puVo.getName());
//            row.createCell(1).setCellValue(puVo.getPv());
//            row.createCell(2).setCellValue(puVo.getUv());
//        }
//
//        // 设置响应头
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=PU_Data.xlsx");
//        headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        // 将工作簿写入到字节数组
//        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
//            workbook.write(outputStream);
//            workbook.close();
//            return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK);
//        }
//    }





}
